// 生成验证码图片的函数
function generateCaptchaImage() {
    const captchaImage = document.getElementById('captchaImage');
    const captchaImageRegister = document.getElementById('captchaImageRegister');
    captchaImage.src = `captcha.php?${new Date().getTime()}`;
    captchaImageRegister.src = `captcha.php?${new Date().getTime()}`;
}

// 页面加载时生成验证码图片
window.onload = function () {
    generateCaptchaImage();
    updateUserCount();
};

// 登录表单提交事件
document.getElementById('loginForm').addEventListener('submit', function (e) {
    e.preventDefault();
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;
    const captcha = document.getElementById('captcha').value;

    // 发送登录请求
    fetch('login.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: `username=${username}&password=${password}&captcha=${captcha}&login=1`
    })
   .then(response => response.text())
   .then(data => {
        if (data === "登录成功") {
            // 登录成功，显示聊天室
            document.getElementById('loginContainer').style.display = 'none';
            document.getElementById('chatContainer').style.display = 'block';
            document.getElementById('usernameDisplay').textContent = username;

            // 将用户ID存储到sessionStorage中
            sessionStorage.setItem('user_id', JSON.parse(sessionStorage.getItem('user_id')));
            sessionStorage.setItem('username', username);

            // 检查是否为管理员
            fetch('checkAdmin.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: `username=${username}`
            })
           .then(response => response.text())
           .then(adminData => {
                if (adminData === "是管理员") {
                    document.getElementById('adminBadge').style.display = 'inline';
                    document.getElementById('adminOperations').style.display = 'block';
                    sessionStorage.setItem('admin', true);
                }
            });

            // 加载聊天记录
            loadChatHistory();

            // 监听发送按钮点击事件
            document.getElementById('sendButton').addEventListener('click', sendMessage);

            // 监听键盘回车事件
            document.getElementById('chatInput').addEventListener('keydown', function (event) {
                if (event.key === 'Enter') {
                    sendMessage();
                }
            });
        } else {
            // 登录失败，显示错误信息
            document.getElementById('errorMessages').textContent = data;
        }
    });
});

// 注册表单提交事件
document.getElementById('registerForm').addEventListener('submit', function (e) {
    e.preventDefault();
    const newUsername = document.getElementById('newUsername').value;
    const newPassword = document.getElementById('newPassword').value;
    const captcha = document.getElementById('captchaRegister').value;

    // 发送注册请求
    fetch('register.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: `newUsername=${newUsername}&newPassword=${newPassword}&captchaRegister=${captcha}&register=1`
    })
   .then(response => response.text())
   .then(data => {
        if (data === "注册成功") {
            // 注册成功，显示登录表单
            document.getElementById('registerContainer').style.display = 'none';
            document.getElementById('loginContainer').style.display = 'block';
        } else {
            // 注册失败，显示错误信息
            document.getElementById('registerErrorMessages').textContent = data;
        }
    });
});

// 发送消息函数
let messageCount = 0;
let lastMessageTime = 0;
function sendMessage() {
    const chatInput = document.getElementById('chatInput').value;
    if (chatInput.trim()!== "") {
        const currentTime = Date.now();
        if (messageCount >= 20 && currentTime - lastMessageTime < 60 * 1000) {
            alert("1分钟内只能发送20条消息");
            return;
        }
        if (chatInput.length > 5000) {
            alert("消息字数不能超过5000字");
            return;
        }
        const userId = sessionStorage.getItem('user_id');
        const username = document.getElementById('usernameDisplay').textContent;

        // 处理 @用户 功能
        const mentionedUsers = chatInput.match(/@(\w+)/g);
        if (mentionedUsers) {
            mentionedUsers.forEach(mention => {
                const mentionedUsername = mention.slice(1);
                // 这里可以添加向被提及用户发送通知等逻辑，暂时简单打印
                console.log(`提及了用户: ${mentionedUsername}`);
            });
        }

        // 发送消息到服务器
        fetch('sendMessage.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: `user_id=${userId}&message=${chatInput}`
        })
       .then(response => response.text())
       .then(data => {
            if (data === "消息发送成功") {
                // 清空输入框
                document.getElementById('chatInput').value = "";
                messageCount++;
                lastMessageTime = currentTime;

                // 加载最新的聊天记录
                loadChatHistory();
            } else {
                console.log('消息发送失败:', data);
            }
        });
    }
}

// 加载聊天记录函数
function loadChatHistory() {
    const chatMessages = document.getElementById('chatMessages');
    chatMessages.innerHTML = "";

    // 从服务器获取聊天记录
    fetch('chatHistory.php')
   .then(response => response.text())
   .then(data => {
        const messages = JSON.parse(data);
        messages.forEach(message => {
            const chatMessage = document.createElement('div');
            chatMessage.classList.add('chat-message');
            if (message.username === document.getElementById('usernameDisplay').textContent) {
                chatMessage.classList.add('me');
            } else {
                chatMessage.classList.add('other');
            }
            chatMessage.textContent = `${message.username}: ${message.message}`;
            chatMessages.appendChild(chatMessage);
        });
    });
}

// 删除用户函数
function deleteUser(userId) {
    if (confirm('确定要删除该用户吗？')) {
        fetch('admin_operations.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: `delete_user=1&user_id=${userId}`
        })
       .then(response => response.text())
       .then(data => {
            alert(data);
            // 刷新用户列表或聊天界面等操作
            loadChatHistory(); // 刷新聊天记录，可能需要根据实际情况调整
        });
    }
}

// 更改密码函数
function changePassword(userId, newPassword) {
    fetch('admin_operations.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: `change_password=1&user_id=${userId}&new_password=${newPassword}`
    })
   .then(response => response.text())
   .then(data => {
        alert(data);
        // 密码更改成功后的操作，比如提示用户重新登录等
        if (data === "密码更改成功") {
            // 这里可以添加让用户重新登录的逻辑，比如跳转到登录页面
            window.location.href = 'login.html';
        }
    });
}

// 注销函数
function logout() {
    fetch('logout.php')
   .then(() => {
        // 清空界面相关数据
        document.getElementById('chatContainer').style.display = 'none';
        document.getElementById('loginContainer').style.display = 'block';
        sessionStorage.removeItem('user_id');
        sessionStorage.removeItem('username');
        sessionStorage.removeItem('admin');
        updateUserCount();
    });
}

// 为删除用户按钮添加点击事件
document.getElementById('deleteUserButton').addEventListener('click', function () {
    const userId = prompt('请输入要删除的用户ID');
    if (userId) {
        deleteUser(userId);
    }
});

// 为更改密码按钮添加点击事件
document.getElementById('changePasswordButton').addEventListener('click', function () {
    const userId = prompt('请输入要更改密码的用户ID');
    const newPassword = prompt('请输入新密码');
    if (userId && newPassword) {
        changePassword(userId, newPassword);
    }
});

// 为注销按钮添加点击事件
document.getElementById('logoutButton').addEventListener('click', logout);

// 私聊功能
function sendPrivateMessage(toUserId) {
    const fromUserId = sessionStorage.getItem('user_id');
    const fromUsername = document.getElementById('usernameDisplay').textContent;
    const toUsername = prompt(`请输入给用户ID为 ${toUserId} 的用户发送的消息`);
    if (toUsername) {
        const privateChatLink = `chatHistory.php?private=true&from=${fromUserId}&to=${toUserId}`;
        const privateChatMessage = document.createElement('a');
        privateChatMessage.href = privateChatLink;
        privateChatMessage.textContent = `${fromUsername} 给 ${toUsername} 发送了一条私聊消息`;
        const chatMessages = document.getElementById('chatMessages');
        chatMessages.appendChild(privateChatMessage);
    }
}

// 显示人数
function updateUserCount() {
    fetch('getUserCount.php')
   .then(response => response.text())
   .then(data => {
        const userCountElement = document.createElement('span');
        userCountElement.textContent = `当前在线人数: ${data}`;
        const chatHeader = document.getElementById('chat-header');
        chatHeader.appendChild(userCountElement);
    });
}

// 用户搜索功能
function searchUser() {
    const searchInput = document.getElementById('searchInput').value;
    // 发送搜索请求到服务器，获取匹配的用户列表
    fetch('searchUser.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: `search=${searchInput}`
    })
   .then(response => response.text())
   .then(data => {
        const userList = document.getElementById('userList');
        userList.innerHTML = "";
        const users = JSON.parse(data);
        users.forEach(user => {
            const userItem = document.createElement('li');
            userItem.textContent = user.username;
            userList.appendChild(userItem);
        });
    });
}

// 为搜索按钮添加点击事件
document.getElementById('searchButton').addEventListener('click', searchUser);

// 为用户列表中的用户添加点击事件以发起私聊
const userList = document.getElementById('userList');
userList.addEventListener('click', function (event) {
    if (event.target.tagName === 'LI') {
        const toUsername = event.target.textContent;
        // 假设从服务器获取用户ID的逻辑，这里简单模拟
        const toUserId = 1; // 实际应根据用户名查询数据库获取
        sendPrivateMessage(toUserId);
    }
});

// 在HTML中添加搜索相关元素
const searchContainer = document.createElement('div');
searchContainer.classList.add('search-container');
const searchInput = document.createElement('input');
searchInput.id ='searchInput';
searchInput.placeholder = '搜索用户';
const searchButton = document.createElement('button');
searchButton.id ='searchButton';
searchButton.textContent = '搜索';
searchContainer.appendChild(searchInput);
searchContainer.appendChild(searchButton);
const chatHeader = document.getElementById('chat-header');
chatHeader.appendChild(searchContainer);

const userListContainer = document.createElement('div');
userListContainer.classList.add('user-list-container');
const userList = document.createElement('ul');
userList.id = 'userList';
userListContainer.appendChild(userList);
chatHeader.appendChild(userListContainer);
